package com.chcit.mobile.mvp.shipment.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chcit.mobile.app.base.ScanToolQueryFragment;
import com.google.android.material.textfield.TextInputEditText;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.spinner.DropDownMenu;

import com.chcit.custom.view.edit.SuperInputEditText;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.app.utils.TimeDialogUtil;
import com.chcit.mobile.di.component.DaggerShipmentComponent;
import com.chcit.mobile.di.module.ShipmentModule;
import com.chcit.mobile.helper.recycler.RecycleViewDivider;
import com.chcit.mobile.mvp.common.model.MenuTypeEnum;
import com.chcit.mobile.mvp.shipment.contract.ShipmentContract;
import com.chcit.mobile.mvp.entity.BpartnerBean;
import com.chcit.mobile.mvp.entity.ShipmentBean;
import com.chcit.mobile.mvp.entity.Statu;
import com.chcit.mobile.mvp.shipment.presenter.ShipmentPresenter;
import com.chcit.mobile.mvp.common.adapter.GirdDropDownAdapter;
import com.chcit.mobile.mvp.shipment.adapter.ShipmentAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 采购出库预览页面
 */
public class ShipmentFragment extends ScanToolQueryFragment<ShipmentPresenter> implements ShipmentContract.View {


    @BindView(R.id.ckb_select_all)
    CheckBox selectAll;
    @BindView(R.id.bt_batch_confirm)
    Button btBatchConfirm;
    @BindView(R.id.linear_layout_show)
    LinearLayout mLinearLayout;
    @BindView(R.id.shipment_dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.lv_receive_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_show_select)
    TextView tvShowSelect;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    ShipmentAdapter mAdapter;
    protected MenuTypeEnum type; //出库类型  采退-PO
    private ArrayList<BpartnerBean> bpartners;
    private TextInputEditText tietProductName;
    private BpartnerBean bpartnerBean;
    private String headers[] = {"选择供应商", "输入商品", "选择日期", "出库类型"};
    private int dateTime;//选择的日期 0没选择  1-1月内  2-2月内  3-3月内
    private ShipmentBean shipmentBean;
    private int REQUEST_CODE = -3;
    private String orderType;
    private String page;
    private Statu user;



    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerShipmentComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .shipmentModule(new ShipmentModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_shipment;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
            pop();
            if (getActivity() != null) {
                _mActivity.finish();
            }
        });
        initDropDownMenu();

    }

    private void initDropDownMenu() {
        final List<View> popupViews = new ArrayList<>();

        //供应商选择
        final ListView wareView = new ListView(getContext());
        bpartners = new ArrayList<>();
        bpartners.add(new BpartnerBean(1, "不限"));
        final GirdDropDownAdapter<BpartnerBean> bpartnerAdapter = new GirdDropDownAdapter<>(getContext(), bpartners);
        wareView.setDividerHeight(0);
        wareView.setAdapter(bpartnerAdapter);
        wareView.setOnItemClickListener((parent, view, position, id) -> {
            bpartnerAdapter.setCheckItem(position);
            bpartnerBean = bpartners.get(position);
            mDropDownMenu.setTabText(position == 0 ? headers[0] : bpartnerBean.getName());
            mDropDownMenu.closeMenu();
        });
        //商品选择
        @SuppressLint("InflateParams") final View constellationView = getLayoutInflater().inflate(R.layout.custom_layout, null);
        tietProductName = constellationView.findViewById(R.id.constellation);
        TextView ok = constellationView.findViewById(R.id.ok);
        ok.setOnClickListener(v -> {
            String text = Objects.requireNonNull(tietProductName.getText()).toString();
            mDropDownMenu.setTabText(text.isEmpty() ? headers[1] : text);
            mDropDownMenu.closeMenu();
        });

        //日期选择
        final ListView dateView = new ListView(getContext());
        List<String> dates = Arrays.asList("不限", "一周内", "二周内", "三周内");
        final GirdDropDownAdapter<String> dateAdapter = new GirdDropDownAdapter<>(getContext(), dates);
        dateView.setDividerHeight(0);
        dateView.setAdapter(dateAdapter);
        dateView.setSelection(1);
        dateView.setOnItemClickListener((parent, view, position, id) -> {
            dateAdapter.setCheckItem(position);
            dateTime = position;
            mDropDownMenu.setTabText(position == 0 ? headers[2] : dates.get(position));
            mDropDownMenu.closeMenu();
        });
        popupViews.add(wareView);
        popupViews.add(constellationView);
        popupViews.add(dateView);

        //入库类型选择
        orderType = type.getType();
        switch (type) {
            case PR:
                mCommonToolbar.setTitleText("采退出库");
                headers = new String[]{"选择供应商", "输入商品", "一周内"};
                page ="pick";
                break;
            case YNCK_SHIPMENT:
                mCommonToolbar.setTitleText("院内出库");
                page ="pick";
                final ListView shipmentTypeView = new ListView(getContext());
                List<Statu> shipmentTypes = new ArrayList<>();
                shipmentTypes.add(new Statu("WO,WR,MO,SO", "全部"));
                shipmentTypes.add(new Statu("WO", "请领"));
                shipmentTypes.add(new Statu("WR", "退库"));
                shipmentTypes.add(new Statu("SO", "领药"));
                shipmentTypes.add(new Statu("MO", "库间调拨"));
                final GirdDropDownAdapter<Statu> receiveTypeAdapter = new GirdDropDownAdapter<>(getContext(), shipmentTypes);
                shipmentTypeView.setDividerHeight(0);
                shipmentTypeView.setAdapter(receiveTypeAdapter);
                shipmentTypeView.setOnItemClickListener((parent, view, position, id) -> {
                    receiveTypeAdapter.setCheckItem(position);
                    orderType = shipmentTypes.get(position).getId();
                    mDropDownMenu.setTabText(position == 0 ? headers[3] : shipmentTypes.get(position).getName());
                    mDropDownMenu.closeMenu();
                });
                popupViews.add(shipmentTypeView);
                break;
        }
        final TextView contentView = new TextView(getContext());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        contentView.setText("");
        //contentView.setBackgroundColor(getResources().getColor(R.color.gray));
        contentView.setGravity(Gravity.CENTER);
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        final List<String> list = Arrays.asList(headers);
        mDropDownMenu.setDropDownMenu(list, popupViews, contentView);

    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
        Objects.requireNonNull(getActivity()).finish();
    }

    @OnClick({R.id.bt_common_query, R.id.bt_batch_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_common_query:
                doQuery();
                break;
          /*  case R.id.bt_receive_date_to:
                Calendar calendarTo = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_to,calendarTo);
                break;
            case R.id.bt_receive_date_from:
                Calendar calendarFrom = Calendar.getInstance();
                TimeDialogUtil.showDatePickerDialog(getActivity(),3,bt_receive_date_from,calendarFrom);
                break;*/
            case R.id.bt_batch_confirm:
                doBatchConfirm();
                break;
        }
    }

    private void doQuery() {
        mAdapter.getData().clear();
        mAdapter.notifyDataSetChanged();
        String pickListNo = Objects.requireNonNull(vetPackageNo.getText()).toString();
        String productName = Objects.requireNonNull(tietProductName.getText()).toString();
        JSONObject data = new JSONObject();
        data.put("page", page);//

        data.put("orderType", orderType);
        if (!pickListNo.isEmpty()) {
            data.put("pickListNo", pickListNo);
        }

        if (!productName.isEmpty()) {
            data.put("productName", productName);
        }
        data.put("start", 0);
        data.put("limit", 1000);
        if (dateTime > 0) {
            String dataArrivedFrom = TimeDialogUtil.getBeforeMonth(dateTime);
            data.put("dataArrivedFrom", dataArrivedFrom);
        }
        if (!productName.isEmpty()) {
            data.put("productName", productName);
        }
        if (bpartnerBean != null) {
            data.put("bpartner", bpartnerBean.getId());
        }
        if (mPresenter != null) {
            mPresenter.getData(data);
        }
    }

    private int itemPosition = 0;

    private void initRecyclerView() {
        mAdapter.setTitleBarView(tvShowSelect);
        //ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(new RecycleViewDivider(mContext, LinearLayoutManager.HORIZONTAL, R.drawable.item_drivide));
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            itemPosition = position;
            if (position >= 0 && adapter.getData().size() > position) {
                toDeal(position);
            }

//                CheckBox checkBox = view.findViewById(R.id.box_puchase_select);
//                checkBox.performClick();
        });
        mRecyclerView.setAdapter(mAdapter);

    }

    /**
     * 当有数据返回时，回调
     *
     * @param requestCode 返回状态码
     * @param resultCode  是否成功状态码
     * @param data        返回数据
     */
    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    onBarcodeEventSuccess(shipmentBean.getPickListNo());
                } else if (mAdapter.getData().size() > 0) {
                    mAdapter.remove(itemPosition);
                    if (mAdapter.getData().size() > 0) {
                        if (mAdapter.getData().size()  > itemPosition) {
                            toDeal(itemPosition);
                        } else {
                            doQuery();
                        }
                    }
                }
            } else if (resultCode == -2) {

                if (mAdapter.getData().size() > ++itemPosition) {
                    toDeal(itemPosition );
                }
            }
        }

    }

    private void toDeal(int position) {

        shipmentBean = mAdapter.getData().get(position);
        if ("Y".equals(shipmentBean.getIsStoragePackage())) {
            startForResult(ShipmentScanPackageFragment.newInstance(shipmentBean), REQUEST_CODE);
        } else {
            startForResult(ShipmentDetailFragment.newInstance(shipmentBean), REQUEST_CODE);
        }
    }

    @Override
    public void updateContentList(List<ShipmentBean> shipmentBeans) {

        mAdapter.addData(shipmentBeans);
        mLinearLayout.setVisibility(View.VISIBLE);

    }

    @Override
    public <T extends View> T getViewByTag(int i) {
        switch (i) {
            case 1:
                return (T) vetPackageNo;
            case 2:
                break;

        }
        return null;
    }

    @Override
    public Context getContext() {
        return mContext;
    }


    private void doBatchConfirm() {
        if(shipmentBean==null){
            shipmentBean = mAdapter.getItem(0);
        }
        final ArrayList<ShipmentBean> datas = mAdapter.getSelectedItem();
        if (datas.size() == 0) {
            DialogUtil.showErrorDialog(getContext(), "请选择至少一项");
            return;
        }
        boolean isSecondChange = false;
        JSONArray lineData = new JSONArray();
        for (ShipmentBean prb : datas) {
            if("Y".equals(prb.getIsStoragePackage())){
                continue;
            }
            if ("Y".equals(prb.getIsControlledProduct())) {
                isSecondChange = true;
            }
            JSONObject params = new JSONObject();
            params.put("pickListJobId", prb.getPickListJobId());
            params.put("qtyConfirm", prb.getQtyLeft());
            params.put("qtyCancel", 0);
            lineData.add(params);

        }
        if(lineData.size()==0){
            DialogUtil.showErrorDialog(getContext(), "包装管理不允许批量收货！");
            return;
        }
//        JSONObject data = new JSONObject();
//        data.put("pickListId", shipmentBean.getPickListId());//任务
//        data.put("lineData", lineData); //拣货数量
//        data.put("isAutoShipment", "N");
        JSONObject data = new JSONObject();
        data.put("pickListId", shipmentBean.getPickListId());//任务
        data.put("lineData", lineData);
        showConfirmDialog(datas, data);
    }

    private void showConfirmDialog(ArrayList<ShipmentBean> datas, JSONObject data) {
        new MaterialDialog.Builder(Objects.requireNonNull(getContext()))
                .title("提示")
                .content("确定要批量提交" + datas.size() + "个商品吗")
                .items(datas)
                // .iconRes(R.drawable.icon)
                .positiveText("确认")
                .negativeText("取消")
                //点击事件添加 方式1
                .onAny((dialog, which) -> {
                    if (which == DialogAction.POSITIVE) {


                        assert mPresenter != null;
                        mPresenter.doBatchConfirm(data, () -> {
                            showMessage("处理成功！");
                            for (int i = mAdapter.getSelectedItemPosition().size() - 1; i + 1 > 0; i--) {

                                mAdapter.remove(mAdapter.getSelectedItemPosition().get(i));

                            }
                        });
                        dialog.dismiss();
                        // Toast.makeText(MainActivity.this, "同意" + dataChoose, Toast.LENGTH_LONG).show();
                    } else if (which == DialogAction.NEGATIVE) {
                        // Toast.makeText(MainActivity.this, "不同意", Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        vetPackageNo.setText(barcodeData);
        btQuery.performClick();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            mCommonToolbar.getLeftMenuView(0).setOnClickListener(l -> {
                pop();
                l.setOnClickListener(null);
                if (getActivity() != null) {
                    _mActivity.finish();
                }

            });
        }
        super.onHiddenChanged(hidden);

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initRecyclerView();
        selectAll.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                mAdapter.checkAll();
            } else {
                mAdapter.cancelAll();
            }
        });
        //etPackageNo.addTextChangedListener(textWatcher);
    }

    private TextWatcher textWatcher = new TextWatcher() {
        int mEditTextHaveInputCount = 0;

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*/
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                if (mEditTextHaveInputCount == 0) {
                    btQuery.setEnabled(false);
                }
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            //EditText最初内容为空 改变EditText内容时 个数加一
            if (TextUtils.isEmpty(s)) {

                mEditTextHaveInputCount++;
                // 判断个数是否到达要求
                int EDITTEXT_AMOUNT = 1;

                if (mEditTextHaveInputCount >= EDITTEXT_AMOUNT) {
                    btQuery.setEnabled(true);
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    public Statu getUser() {
        return user;
    }

    public void setUser(Statu user) {
        this.user = user;
    }

}
